package com.ayoka.parenting.ui.group.topic.publish;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.ayoka.parenting.R;
import com.ayoka.parenting.adapter.PickPictureAdapter;
import com.ayoka.parenting.bean.PublishTopicBean;
import com.ayoka.parenting.databinding.ActivityPublishTopicBinding;
import com.ayoka.parenting.interf.SimpleTextWatchListener;
import com.ayoka.parenting.mvp.MVPBaseActivity;
import com.jincp.common.brvah.BaseQuickAdapter;
import com.jincp.common.model.ToolBarOptions;
import com.jincp.common.permission.MPermission;
import com.jincp.common.utils.LiveDataBus;
import com.jincp.filepicker.bean.BaseFile;
import com.jincp.filepicker.ui.image.ImagePickerManager;
import com.jincp.image.showImage.ShowPictureActivity;

import java.io.File;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * @ProjectName: MVPPlugin.
 * @ClassName: PublishTopicActivity.
 * @Description: .
 * @Author: jincp.
 * @CreateDate: 2019/10/10 18:17.
 */
public class PublishTopicActivity extends MVPBaseActivity<ActivityPublishTopicBinding, PublishTopicContract.View, PublishTopicPresenter> implements PublishTopicContract.View, Observer {

    private String[] permission = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};

    public static void start(Activity activity, String circleGroupId) {
        Intent intent = new Intent(activity, PublishTopicActivity.class);
        intent.putExtra("CircleGroupId", circleGroupId);
        activity.startActivity(intent);
    }

    private String circleGroupId;

    private PickPictureAdapter pickPictureAdapter;

    private MenuItem menuPublish;

    @Override
    protected void configIntentValue() {
        Intent intent = getIntent();
        if (intent != null) {
            circleGroupId = getIntent().getStringExtra("CircleGroupId");
        }
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_publish_topic;
    }


    @Override
    protected void initViews() {

        mDataBinding.edtContent.addTextChangedListener(new SimpleTextWatchListener() {

            @Override
            public void afterTextChanged(Editable s) {
                // 如果图片不为空 或者 文字不为空
                if (menuPublish != null) {
                    menuPublish.setEnabled(!pickPictureAdapter.getData().isEmpty() || s.length() != 0);
                }
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        ToolBarOptions options = new ToolBarOptions(R.string.publish_topic);
        setCustomToolBar(mDataBinding.customToolbar.toolbar, options);

        ImagePickerManager.getInstance().addObserver(this);
        configPictureRecyclerView();
        pickPictureAdapter.addData(0, "");
    }

    private void configPictureRecyclerView() {
        mDataBinding.recyclerViewPicture.setLayoutManager(new GridLayoutManager(this, 3));
        pickPictureAdapter = new PickPictureAdapter();
        pickPictureAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.iv_delete_picture) {
                    ((PickPictureAdapter) adapter).deletePicture(position);
                } else if (view.getId() == R.id.rl_has_picture) {
                    ShowPictureActivity.start(PublishTopicActivity.this, ((PickPictureAdapter) adapter).getPictureUrlList(), position, new ShowPictureActivity.ImageSize(720, 720));
                } else if (view.getId() == R.id.rl_add_picture) {
                    if (MPermission.hasPermissions(PublishTopicActivity.this, permission)) {
                        mPresenter.showPickPicturePopup(getSupportFragmentManager());
                    } else {
                        MPermission.with(PublishTopicActivity.this)
                                .permissions(permission)
                                .request();
                    }
                }
            }
        });
        mDataBinding.recyclerViewPicture.setAdapter(pickPictureAdapter);
    }

    @Override
    protected PublishTopicPresenter getPresenter() {
        return new PublishTopicPresenter();
    }

    @Override
    public void onPickPhotoItemClick(int itemValue) {
        if (itemValue == ImagePickerManager.FROM_CAMERA) {
            ImagePickerManager.getInstance().setMultiMode(false).setCleanSelectedItem(true).takePicture(this);
        } else if (itemValue == ImagePickerManager.FROM_LOCAL) {
            ImagePickerManager.getInstance().setMultiMode(false).setCleanSelectedItem(true).pickPicture(this);
        }
    }

    @Override
    public void configCompressList(boolean isSuccess, List<String> compressedImagePathList) {
        if (isSuccess) {
            for (String path : compressedImagePathList) {
                pickPictureAdapter.addData(0, path);
            }
            if (pickPictureAdapter.getData().size() > 1) {
                pickPictureAdapter.remove(1);
            }
        }
    }

    @Override
    public void onPublishTopicCallback(boolean isSuccess, PublishTopicBean response) {
        if (isSuccess && response != null) {
            showToast("发表成功！");
            LiveDataBus.getInstance().with("Topic", String.class).postValue(response.topic_id);
            finishDelay();
        }
    }

    private void publishTopic() {
        String content = mDataBinding.edtContent.getText().toString().trim();
        File file = null;
        if (!pickPictureAdapter.getData().isEmpty()) {
            String path = pickPictureAdapter.getItem(0);
            if (!TextUtils.isEmpty(path)) {
                file = new File(path);
            }
        }
        if (mPresenter != null) {
            mPresenter.publishTopic(circleGroupId, content, file);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_publish_topic, menu);//加载menu文件到布局
        menuPublish = menu.getItem(0);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        if (item.getItemId() == R.id.action_publish) {
            publishTopic();
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ImagePickerManager.getInstance().onActivityResult(this, requestCode, resultCode, data);
    }

    @Override
    public void update(Observable observable, Object arg) {
        if (observable instanceof ImagePickerManager) {
            if (TextUtils.equals("Completed", (String)arg)) {
                List<BaseFile> selectedFileList = ((ImagePickerManager) observable).getSelectedFileList();
                if (mPresenter != null) {
                    mPresenter.configFileList(selectedFileList);
                }
            }
        }
    }
}
